import { formatReqLog, selectQueryFunc, verifyAuthentication, mkdirs, replaceSpecialCharacters } from '../util/';
import dayjs from 'dayjs';

// 添加数据
const addData = async (req: any, res: any) => {
    console.log(req.body);
    let data = req.body;
    let position = JSON.stringify(data.position);
    let measureValue = JSON.stringify(data.measureValue);
    addMeasureData(data.type, data.name, data.address, position, measureValue, res)
}

const addMeasureData = async (type: string, name: string, address: string, position: string, measureValue: string, res: any) => {
    const selectQuery = `SELECT * FROM zn_measure WHERE [name]='${name}'`;
    try {
        const isName = await selectQueryFunc(selectQuery);
        if (!isName.data) {
            const addQuery = `
        INSERT INTO zn_measure (type, name, address, position, measureValue, createTime)
          VALUES (
            '${type}',
            '${name}',
            '${address}',
            '${position}',
            '${measureValue}',
            '${dayjs().format('YYYY-MM-DD HH:mm:ss')}'
          )
      `;
            await selectQueryFunc(addQuery, (insertErr, _) => {
                if (insertErr) {
                    res.send(formatReqLog(300, '添加失败', insertErr, { data: insertErr }));
                } else {
                    res.send(formatReqLog(200, '添加' + type + '数据成功', null, { name }));
                }
            });
        }
    } catch (err) {
        formatReqLog(501, '超级管理员数据初始化新增失败', err, { user: 'system' });
    }
}

// 查询数据
const findData = async (req: any, res: any) => {
    console.log(req.query);
    const page = req.query.page || 1; // 页码
    const limit = req.query.limit || 10; // 每页行数
    const name = String(req.query.name || '') || '';
    const address = String(req.query.address || '') || '';
    const type = String(req.query.type || '') || '';
    const field = req.query.field || ''; // 索引排序，没有则为空，这里默认转为id索引排序
    const order = req.query.order ? 'ASC' : 'DESC'; // 不传默认按倒序排列，true顺序排列

    const queryCondition = [] as string[]; // 暂存查询的字段
    // 验证头部是否有token
    const mine = await verifyAuthentication(req.headers.authorization || req.headers.token) as { err, data; };
    // if (!mine.data) return res.send(formatReqLog(401, 'token已过期', null, { goal: req.originalUrl }));
    if (name) queryCondition.push(`[name] LIKE '%${name}%'`);
    if (address) queryCondition.push(`[address] LIKE '%${address}%'`);
    if (type) queryCondition.push(`[type] LIKE '%${type}%'`);
    const selectQuery = `
        SELECT TOP ${limit} *
        FROM (
            SELECT *, ROW_NUMBER() OVER (ORDER BY ${field || 'id'} ${order}) AS rownum
            FROM zn_measure
            ${(queryCondition.length) ? `WHERE ${queryCondition.join(' AND ')}` : ''}
        ) AS numbered
        WHERE rownum > ${(page - 1) * limit};
        `;
    await selectQueryFunc(selectQuery, async (insertErr, { recordset }) => {
        if (insertErr) {
            res.send(formatReqLog(300, '查询失败', insertErr, { goal: req.originalUrl, sql: selectQuery }));
        } else {
            const { data } = await selectQueryFunc(`
                SELECT COUNT(*) AS total_count FROM zn_measure ${(queryCondition.length) ? `WHERE ${queryCondition.join(' AND ')}` : ''}
            `);
            recordset.forEach((item: any) => {
                item.position = JSON.parse(item.position);
                item.measureValue = JSON.parse(item.measureValue);
            });
            res.send(formatReqLog(200, '查询成功', recordset, {
                goal: req.originalUrl, total: data.total_count
            }));
        }
    })
}

// 删除数据
const deleteData = async (req: any, res: any) => {
    const data = req.query;
    console.log(data)
    if (data.id) {
        const isExist = await selectQueryFunc(`SELECT COUNT(*) FROM zn_measure WHERE id = ${data.id}`);
        console.log(isExist.data[''])
        if (isExist.data[''] == 0) { res.send(formatReqLog(300, '此id已被删除', null, {})); return }

        const upQuery = `DELETE zn_measure WHERE id=${data.id}`;
        await selectQueryFunc(upQuery, (insertErr, _) => {
            if (insertErr) {
                res.send(formatReqLog(300, '删除失败', insertErr, { goal: req.originalUrl, sql: upQuery }));
            } else {
                res.send(formatReqLog(200, '删除成功', null, { goal: req.originalUrl }));
            }
        });
    } else {
        res.send(formatReqLog(300, '删除失败,请传入标识id', null, {}));
    }
}

// 编辑数据
const editData = async (req: any, res: any) => {
    const data = req.body.data || req.body || {};
    console.log(data);
    // 存储旧数据
    // const oldMeasureData = await selectQueryFunc(`SELECT * FROM zn_measure WHERE id=${data.id}`);
    if (data.id) {
        const upQuery = `
        UPDATE zn_measure SET name='${data.name}',
          address='${data.address}' 
          WHERE id=${data.id}
        `;
        selectQueryFunc(upQuery, (insertErr, _) => {
            if (insertErr) {
                res.send(formatReqLog(300, '修改失败', insertErr, { goal: req.originalUrl, sql: upQuery }));
            } else {
                res.send(formatReqLog(200, '修改成功', null, { goal: req.originalUrl }));
            }
        });
    } else {
        res.send(formatReqLog(400, '传参有误', null, {}));
    }
}


export = {
    addData,
    findData,
    deleteData,
    editData
};